/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.knowledge.doc.controller;

import com.wallellen.core.page.OperateType;
import com.wallellen.core.page.RequestMode;
import com.wallellen.core.page.ViewMode;
import com.wallellen.core.sql.query.DBRule;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.core.time.TimeTool;
import com.wallellen.knowledge.doc.domain.Doc;
import com.wallellen.knowledge.doc.domain.DocText;
import com.wallellen.knowledge.doc.domain.DocType;
import com.wallellen.knowledge.doc.domain.ex.DocEntire;
import com.wallellen.knowledge.doc.server.DocManagerInter;
import com.wallellen.knowledge.doc.server.DocOperateRightInter;
import com.wallellen.knowledge.doc.server.DocTypeInter;
import com.wallellen.knowledge.doc.server.DocgroupManagerInter;
import com.wallellen.web.WebUtils;
import com.wallellen.web.easy.EasyUiUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 文档管理
 *
 * @author <a href="mailto:wallellen@hotmail.com">WALLE</a>
 */
@RequestMapping("/doc")
@Controller
public class ActionDocQuery extends WebUtils {
    @Resource
    private DocManagerInter docManagerImpl;
    @Resource
    private DocOperateRightInter docOperateRightImpl;
    @Resource
    private DocgroupManagerInter docgroupManagerImpl;
    @Resource
    private DocTypeInter docTypeManagerImpl;

    private static final Logger log = LoggerFactory.getLogger(ActionDocQuery.class);

    /**
     * 查询结果集合
     *
     * @return
     */
    @RequestMapping("/query")
    @ResponseBody
    public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) {
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            DataResult result = docManagerImpl.createSimpleDocQuery(query).search();
            result.runDictionary("1:开放,0:禁用,2:待审核", "STATE");
            result.runDictionary("1:HTML,2:TXT,3:html站点,4:小组首页,5:资源文件", "DOMTYPE");
            result.runDictionary("1:分类,0:本人,2:小组,3:禁止", "WRITEPOP");
            result.runDictionary("1:分类,0:本人,2:小组,3:禁止", "READPOP");
            result.runformatTime("PUBTIME", "yyyy-MM-dd HH:mm:ss");
            return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping("/list")
    public ModelAndView index(HttpSession session) {
        return ViewMode.getInstance().returnModelAndView("doc/DocTResult");
    }

    /**
     * 提交修改数据
     *
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Map<String, Object> editSubmit(Doc entity, HttpSession session, String content) {
        try {
            DocEntire doc = new DocEntire(entity);
            Doc dbdoc = docManagerImpl.getDocOnlyBean(entity.getId());
            doc.getDoc().setCuser(dbdoc.getCuser());
            doc.getDoc().setCusername(dbdoc.getCusername());
            doc.setTexts(new DocText(content, TimeTool.getTimeDate14(), TimeTool.getTimeDate14(),
                    getCurrentUser(session).getName(), getCurrentUser(session).getId(),
                    getCurrentUser(session).getName(), getCurrentUser(session).getId(), "1"));
            doc = docManagerImpl.editDoc(doc, "系统管理员修改", getCurrentUser(session));
            return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", doc).returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage()).returnObjMode();
        }
    }

    /**
     * 提交修改数据
     *
     * @return
     */
    @RequestMapping("/FarmDocRighteditCommit")
    @ResponseBody
    public Map<String, Object> rightEditCommit(Doc entity, HttpSession session, String ids) {
        try {
            for (String id : parseIds(ids)) {
                entity = docOperateRightImpl.editDocRight(id, DocOperateRightInter.POP_TYPE.getEnum(entity.getReadpop()),
                        DocOperateRightInter.POP_TYPE.getEnum(entity.getWritepop()), getCurrentUser(session));
            }
            return ViewMode.getInstance().setOperate(OperateType.ADD).returnObjMode();

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage()).returnObjMode();
        }
    }

    /**
     * 提交新增数据
     *
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Map<String, Object> addSubmit(Doc entity, HttpSession session, String content, String doctypeId) {
        try {
            DocEntire doc = new DocEntire(entity);
            // 构造文档text
            doc.setTexts(new DocText(content, TimeTool.getTimeDate14(), TimeTool.getTimeDate14(),
                    getCurrentUser(session).getName(), getCurrentUser(session).getId(),
                    getCurrentUser(session).getName(), getCurrentUser(session).getId(), "1"));
            // 构造分类
            if (doctypeId != null && !doctypeId.isEmpty()) {
                doc.setType(docTypeManagerImpl.getType(doctypeId));
            }

            if ("".equals(doc.getDoc().getImgid())) {
                doc.getDoc().setImgid(null);
            }
            doc = docManagerImpl.createDoc(doc, getCurrentUser(session));
            return ViewMode.getInstance().putAttr("entity", doc).returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

    /**
     * 删除数据
     *
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public Map<String, Object> delSubmit(String ids, HttpSession session) {
        try {
            for (String id : parseIds(ids)) {
                docManagerImpl.deleteDocNoPop(id, getCurrentUser(session));
            }
            return ViewMode.getInstance().returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

    /**
     * （修改文档权限）
     *
     * @return
     */
    @RequestMapping("/FarmDocRightedit")
    public ModelAndView rightEdit(DocType doctype, String ids) {
        try {
            if (doctype != null && doctype.getId() != null && doctype.getId().trim().length() > 0) {
            }
            @SuppressWarnings("deprecation")
            DocEntire entity = docManagerImpl.getDoc(ids);
            doctype = entity.getType();
            RequestMode pageset = new RequestMode();
            pageset.setOperateType(2);

            return ViewMode.getInstance().putAttr("entity", entity).putAttr("doctype", doctype)
                    .putAttr("pageset", pageset).returnModelAndView("doc/DocTRightSetPage");
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnModelAndView("doc/DocTRightSetPage");
        }
    }

    /**
     * 显示详细信息（修改或浏览时）
     *
     * @return
     */
    @SuppressWarnings("deprecation")
    @RequestMapping("/form")
    public ModelAndView view(RequestMode pageset, HttpServletRequest request, DataQuery query, HttpSession session,
                             DocType doctype, String ids) {
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            query.setPagesize(100);
            query.addRule(new DBRule("b.userid", getCurrentUser(session).getId(), "="));
            DataResult result = docgroupManagerImpl.createDocgroupQueryJoinUser(query).search();
            String typeid = null;
            if (doctype != null && doctype.getId() != null && doctype.getId().trim().length() > 0) {
                typeid = doctype.getId();
            }
            switch (pageset.getOperateType()) {
                case (1): {// 新增
                    doctype = docTypeManagerImpl.getType(typeid);
                    DocEntire entity = new DocEntire(new Doc());
                    entity.getDoc()
                            .setPubtime(TimeTool.getFormatTimeDate12(TimeTool.getTimeDate14(), "yyyy-MM-dd HH:mm:ss"));
                    entity.getDoc().setAuthor(getCurrentUser(session).getName());
                    return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", entity)
                            .putAttr("doctype", doctype).putAttr("result", result).returnModelAndView("doc/DocTForm");
                }
                case (0): {// 展示
                    DocEntire entity = docManagerImpl.getDoc(ids);
                    if (entity.getDoc().getPubtime() != null && entity.getDoc().getPubtime().trim().length() > 0) {
                        entity.getDoc().setPubtime(
                                TimeTool.getFormatTimeDate12(entity.getDoc().getPubtime(), "yyyy-MM-dd HH:mm:ss"));
                    }
                    doctype = entity.getType();
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", docManagerImpl.getDoc(ids)).putAttr("result", result)
                            .putAttr("doctype", doctype).returnModelAndView("doc/DocTForm");
                }
                case (2): {// 修改
                    DocEntire entity = docManagerImpl.getDoc(ids);
                    if (entity.getDoc().getPubtime() != null && entity.getDoc().getPubtime().trim().length() > 0) {
                        entity.getDoc().setPubtime(
                                TimeTool.getFormatTimeDate12(entity.getDoc().getPubtime(), "yyyy-MM-dd HH:mm:ss"));
                    }
                    doctype = entity.getType();
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", docManagerImpl.getDoc(ids)).putAttr("result", result)
                            .putAttr("doctype", doctype).returnModelAndView("doc/DocTForm");
                }
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ViewMode.getInstance().setError(e + e.getMessage()).returnModelAndView("doc/DocTForm");
        }
        return ViewMode.getInstance().returnModelAndView("doc/DocTForm");
    }

    @RequestMapping("/toKindEditor")
    public ModelAndView toKindEditor(HttpSession session) {
        return ViewMode.getInstance().returnModelAndView("doc/DocTkindeditor");
    }

    @RequestMapping("/toManagerDocMsg")
    public ModelAndView toManagerDocMsg(HttpSession session, String ids) {
        return ViewMode.getInstance().putAttr("ids", ids).returnModelAndView("doc/DocTCommentSetPage");
    }

    /**
     * 删除附件
     *
     * @return Map<String,Object>
     */
    @RequestMapping("/delImg")
    @ResponseBody
    public Map<String, Object> delImg(String imgid) {
        try {
            docManagerImpl.delImg(imgid);
            return ViewMode.getInstance().returnObjMode();
        } catch (Exception e) {
            log.error(e.toString());
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

}
